package siau.android.base;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import hhm.android.base.activity.mainActivity.MainActivity;
import hhm.android.library.LogUtils;
import hhm.android.library.calendar.DateUtil;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import siau.android.http.FlutterWXShareModel;
import siau.android.http.model.ChildModel;
import siau.android.http.model.FlutterUrlModel;
import siau.android.http.model.UrlModel;
import siau.android.library.KeyString;

import static siau.android.base.SBStaticKt.MAIN_ROUTER;
import static siau.android.base.SBStaticKt.WEBVIEW_ROUTER;

public class MyMethodChannel implements MethodChannel.MethodCallHandler {

    public static String CHANNEL = KeyString.flutterBridge;

    private static MethodChannel channel;

    private Activity context;

    /**
     * val i = Intent(this, MyFlutterActivity::class.java)
     * i.putExtra("route", "someActivity&&&")
     * startActivity(i)
     */

    private MyMethodChannel(Activity context) {
        this.context = context;
    }

    public static MyMethodChannel registerWith(Activity context, BinaryMessenger messenger) {
        channel = new MethodChannel(messenger, CHANNEL);
        MyMethodChannel instance = new MyMethodChannel(context);
        //setMethodCallHandler在此通道上接收方法调用的回调
        channel.setMethodCallHandler(instance);
        return instance;
    }

    public void release() {
        if (null != channel) {
            channel.setMethodCallHandler(null);
            channel = null;
        }
    }

    @Override
    public void onMethodCall(MethodCall call, MethodChannel.Result result) {
        LogUtils.Companion.e("hhm", "call.method       " + call.method);
        switch (call.method) {
            case KeyString.ToBackVC:
                if (!TextUtils.isEmpty((String) call.arguments)) {
                    Bundle b = new Bundle();
                    b.putString(KeyString.type, KeyString.community);
                    b.putString(KeyString.data, (String) call.arguments);
                    ARouter.getInstance().build(MAIN_ROUTER).with(b).withFlags(Intent.FLAG_ACTIVITY_NEW_TASK).navigation();
                }
                context.onBackPressed();
                break;
            case KeyString.OnePointHappen:
                String errStr = (String) call.arguments;
                Toast.makeText(SBApplication.applicationContext, context.getString(R.string.login_another_place), Toast.LENGTH_SHORT).show();
                SBApplication.Companion.sendOnePointReceiver(false);
                break;
            case KeyString.SetTitleWhiteAndTextBlank:
                MyFlutterActivity.Companion.getStatusBarStatus().postValue(0);
                break;
            case KeyString.SetTitleBlankAndTextWhite:
                MyFlutterActivity.Companion.getStatusBarStatus().postValue(1);
                break;
            case KeyString.SetTitleTransAndTextWhite:
                MyFlutterActivity.Companion.getStatusBarStatus().postValue(2);
                break;
            case KeyString.SetTitleTransAndTextBlank:
                MyFlutterActivity.Companion.getStatusBarStatus().postValue(3);
                break;
            case KeyString.WebView:
                String jsonStr = (String) call.arguments;
                FlutterUrlModel model = new Gson().fromJson(jsonStr, FlutterUrlModel.class);
                Bundle bundle = new Bundle();
                bundle.putBoolean(KeyString.share, true);
                bundle.putSerializable(KeyString.data, model);
                ARouter.getInstance().build(WEBVIEW_ROUTER).with(bundle).withFlags(Intent.FLAG_ACTIVITY_NEW_TASK).navigation();
                break;
            case KeyString.jumpToTaoBao:
                String arguments = (String) call.arguments;
                UrlModel urlModel = new Gson().fromJson(arguments, UrlModel.class);
                if (urlModel.getUrl().startsWith("taobao")) {
                    if (SystemUtil.isPkgInstalled(context, "com.taobao.taobao")) {
                        SystemUtil.gotoShop(context, urlModel.getUrl());
                    } else {
                        Toast.makeText(context, "您还没有安装淘宝客户端！", Toast.LENGTH_SHORT).show();
                    }
                } else if (urlModel.getUrl().startsWith("openapp.jdmobile")) {
                    if (SystemUtil.isPkgInstalled(context, "com.jingdong.app.mall")) {
                        SystemUtil.gotoShop(context, urlModel.getUrl());
                    } else {
                        Toast.makeText(context, "您还没有安装京东客户端！", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            case KeyString.GetBaseInfo:
                //返回给flutter的参数
                HashMap<String, String> map = new HashMap<>();
                map.put("token", KeyString.token);
                map.put("baseUrl", HttpHelper.baseUrl);
                result.success(map);
                break;
            case KeyString.GetHttpParams:
                //返回给flutter的参数
                HashMap<String, Object> m = new HashMap<>();
                m.put("defaultChildId", SBApplication.Companion.getCommunityChildId());
                result.success(m);
                break;
            case KeyString.GetMyPageParams:
                HashMap<String, Object> hm = new HashMap<>();
                hm.put("defaultChildId", SBApplication.Companion.getCommunityChildId());
                hm.put("userName", SBApplication.Companion.getUserData().getNickName());
                hm.put("userAvatar", TextUtils.isEmpty(SBApplication.Companion.getUserData().getAvatarUrl()) ? "" : SBApplication.Companion.getUserData().getAvatarUrl());
                if (SBApplication.Companion.getUserData().getChildren().size() == 0) {
                    hm.put("babyBirthday", "");
                } else {
                    long time = 0L;
                    ArrayList<ChildModel> children = SBApplication.Companion.getUserData().getChildren();
                    for (int i = 0; i < children.size(); i++) {
                        if (children.get(i).getChildId() == SBApplication.Companion.getCommunityChildId()) {
                            time = children.get(i).getBirthday();
                        }
                    }
                    int s = DateUtil.getMonthDiff(new Date(time), new Date());
                    String babyBirthday;
                    if (s > 35) {
                        babyBirthday = (s / 12) + "岁";
                    } else {
                        babyBirthday = s + "个月";
                    }
                    hm.put("babyBirthday", babyBirthday);
                }
                result.success(hm);
                break;
            case KeyString.QuestionAnswerDetailPage:
                Intent i = new Intent(SBApplication.applicationContext, MyFlutterActivity.class);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                i.putExtra(KeyString.route, KeyString.QuestionAnswerDetailPage + "&&&" + call.arguments);
                SBApplication.applicationContext.startActivity(i);
                break;
            case KeyString.MyPage:
                Intent i2 = new Intent(SBApplication.applicationContext, MyFlutterActivity.class);
                i2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                i2.putExtra(KeyString.route, KeyString.MyPage);
                SBApplication.applicationContext.startActivity(i2);
                break;
            case KeyString.SearchPage:
                Intent iSearchPage = new Intent(SBApplication.applicationContext, MyFlutterActivity.class);
                iSearchPage.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                iSearchPage.putExtra(KeyString.route, KeyString.SearchPage);
                SBApplication.applicationContext.startActivity(iSearchPage);
                break;
            case KeyString.InputPage_TypeQAAsk:
                Intent i3 = new Intent(SBApplication.applicationContext, MyFlutterActivity.class);
                i3.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                i3.putExtra(KeyString.route, KeyString.InputPage_TypeQAAsk);
                SBApplication.applicationContext.startActivity(i3);
                break;
            case KeyString.HotTopicDetailPage:
                Intent i4 = new Intent(SBApplication.applicationContext, MyFlutterActivity.class);
                i4.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                i4.putExtra(KeyString.route, KeyString.HotTopicDetailPage + "&&&" + call.arguments);
                SBApplication.applicationContext.startActivity(i4);
                break;
            case KeyString.VideoDetailPage:
                Intent i5 = new Intent(SBApplication.applicationContext, MyFlutterActivity.class);
                i5.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                i5.putExtra(KeyString.route, KeyString.VideoDetailPage + "&&&" + call.arguments);
                SBApplication.applicationContext.startActivity(i5);
                break;
            case KeyString.ArticleDetailPage:
                Intent i6 = new Intent(SBApplication.applicationContext, MyFlutterActivity.class);
                i6.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                i6.putExtra(KeyString.route, KeyString.ArticleDetailPage + "&&&" + call.arguments);
                SBApplication.applicationContext.startActivity(i6);
                break;
            case KeyString.WXFriendShare:
                FlutterWXShareModel flutterWXShareModel = new Gson().fromJson((String) call.arguments, FlutterWXShareModel.class);
                //初始化一个WXWebpageObject填写url
                WXWebpageObject webpageObject = new WXWebpageObject();
                webpageObject.webpageUrl = flutterWXShareModel.getWxUrl();
                //用WXWebpageObject对象初始化一个WXMediaMessage
                WXMediaMessage msg = new WXMediaMessage(webpageObject);
                msg.title = flutterWXShareModel.getWxTitle();
                msg.description = flutterWXShareModel.getWxDes();
                Glide.with(SBApplication.applicationContext).asBitmap().load(flutterWXShareModel.getImage()).into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        msg.setThumbImage(resource);
                        SendMessageToWX.Req req = new SendMessageToWX.Req();
                        req.transaction = String.valueOf(System.currentTimeMillis());
                        req.message = msg;
                        req.scene = SendMessageToWX.Req.WXSceneTimeline;
                        SBApplication.api.sendReq(req);
                    }
                });
                break;
            case KeyString.WXChatShare:
                FlutterWXShareModel fwsm = new Gson().fromJson((String) call.arguments, FlutterWXShareModel.class);
                //初始化一个WXWebpageObject填写url
                WXWebpageObject wo = new WXWebpageObject();
                wo.webpageUrl = fwsm.getWxUrl();
                //用WXWebpageObject对象初始化一个WXMediaMessage
                WXMediaMessage wxmsg = new WXMediaMessage(wo);
                wxmsg.title = fwsm.getWxTitle();
                wxmsg.description = fwsm.getWxDes();
                Glide.with(SBApplication.applicationContext).asBitmap().load(fwsm.getImage()).into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        wxmsg.setThumbImage(resource);
                        SendMessageToWX.Req req = new SendMessageToWX.Req();
                        req.transaction = String.valueOf(System.currentTimeMillis());
                        req.message = wxmsg;
                        req.scene = SendMessageToWX.Req.WXSceneSession;
                        SBApplication.api.sendReq(req);
                    }
                });
                break;
            default:
                result.notImplemented();
                break;
        }
    }

    public void invokeMethod(@NotNull String methodName, @NotNull String jsonData) {
        channel.invokeMethod(methodName, jsonData);
    }
}